package com.thread;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: leetcode
 * @description:
 * @author: wangzhihua
 * @date: 2022-12-16
 */
public class PrintSorted2 {

	private List<MyLock> myLockList;

	@Test
	public void test() {
		int threadNum = 10;
		myLockList = new ArrayList<>(threadNum);
		initThread(threadNum);
		synchronized (myLockList.get(0)) {
			myLockList.get(0).notify();
		}
	}

	public class Node {
		int val;
		Node next;
	}

	private class MyLock {
		private String name = "";
		public MyLock(String name) {
			this.name = name;
		}
	}

	public void initThread(int threadNum) {
		for (int i = 0; i < threadNum; ++i) {
			myLockList.add(new MyLock("thread - " + (i + 1)));
		}

		List<Thread> threadList = new ArrayList<>(threadNum);
		for (int i = 0; i < threadNum; ++i) {
			final int x = i;
			threadList.add(new Thread(() -> {
				while (true) {
					MyLock curLock = myLockList.get(x);
					synchronized (curLock) {
						try {
							curLock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(curLock.name);

					MyLock nextLock = myLockList.get((x + 1) % threadNum);
					synchronized (nextLock) {
						nextLock.notify();
						System.out.println(nextLock.name + " notify");
					}
				}
			}));
		}

		for (Thread thread : threadList) {
			thread.start();
		}
	}

}
